package cn.example.practice;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;

import java.io.File;

public class TomcatEmbedServer {
    private static Tomcat tomcat = new Tomcat();
    private int port = 8080;

    public TomcatEmbedServer() {
        tomcat = new Tomcat();
    }

    public TomcatEmbedServer(int port) {
        tomcat = new Tomcat();
        this.port = port;
    }

    public void start() throws LifecycleException {
        // 设置端口
        tomcat.setPort(port);
        tomcat.getConnector();

        // 创建上下文
        String webappDirLocation = "web";
        String docBase = new File(webappDirLocation).getAbsolutePath();
        Context context = tomcat.addWebapp("", docBase);

        // 设置 WEB-INF classes 目录
        String projectName = new File("").getAbsolutePath();
        projectName = projectName.substring(projectName.lastIndexOf(File.separator) + 1);
        File additionWebInfClasses = new File("out/production/" + projectName);
        WebResourceRoot resources = new StandardRoot(context);

        // 将实际的类文件目录映射到Tomcat的虚拟路径/WEB-INF/classes
        // 这样Tomcat就知道在哪里找到编译后的Servlet和其他类文件
        resources.addPreResources(new DirResourceSet(resources, "/WEB-INF/classes", additionWebInfClasses.getAbsolutePath(), "/"));
        context.setResources(resources);

        // 启动服务器
        tomcat.start();
        tomcat.getServer().await();
    }

    public static void stop() throws LifecycleException {
        tomcat.stop();
        tomcat.destroy();
    }

    public static void main(String[] args) {
        //jvm hook close stop()
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                stop();
            } catch (LifecycleException e) {
                e.printStackTrace();
            }
        }));

        try {
            TomcatEmbedServer server = new TomcatEmbedServer();
            server.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
